package ts

import (
	"fmt"
	"gitee.com/xiaochengtech/unified-structure/src/common"
	"gitee.com/xiaochengtech/unified-structure/src/util"
	"log"
	"strings"
)

// 基础类型转换
func convertBasicType(varType string) string {
	switch varType {
	case common.VarTypeString, common.VarTypeJson:
		return "string"
	case common.VarTypeUint8, common.VarTypeUint16, common.VarTypeUint32, common.VarTypeUint64, common.VarTypeInt8, common.VarTypeInt16, common.VarTypeInt32, common.VarTypeInt64, common.VarTypeFloat32, common.VarTypeFloat64:
		return "number"
	case common.VarTypeBool:
		return "boolean"
	case common.VarTypeAny:
		return "any"
	default:
		return ""
	}
}

// 复杂类型转换
func convertComplexType(varType string, item common.Field) (finalType string, isRef bool) {
	if util.IsOther(varType) {
		log.Fatalln("不支持JS类型转换" + varType)
		return
	} else if util.IsArray(varType) {
		innerType := varType[2:]
		innerConvertType, needConvert := convertBasicAndReferenceType(innerType, item)
		return innerConvertType + "[]", needConvert
	} else if util.IsMap(varType) {
		mapParts := strings.Split(varType, "]")
		if len(mapParts) != 2 || len(mapParts[0]) <= 4 {
			log.Fatalln("错误的map类型" + varType)
		}
		keyType := convertBasicType(mapParts[0][4:])
		valueType, needConvert := convertBasicAndReferenceType(mapParts[1], item)
		return fmt.Sprintf("{[key: %s]: %s}", keyType, valueType), needConvert
	} else {
		return convertBasicAndReferenceType(varType, item)
	}
}

func convertBasicAndReferenceType(varType string, item common.Field) (finalType string, isRef bool) {
	basicType := convertBasicType(varType)
	if len(basicType) != 0 {
		return basicType, false
	}
	if util.IsReference(varType) {
		return getReferName(item), true
	}
	log.Fatalln("错误的最终类型" + varType)
	return
}

func getReferName(item common.Field) string {
	if len(item.Refer.Name) == 0 {
		log.Fatalln("refer.name必须存在", item.Name)
	}
	return item.Refer.Name
}
